import json
import pymysql
import requests
from playwright.sync_api import sync_playwright
import redis

redis_con = redis.Redis(host='127.0.0.1',
                        port=6379, db=2, decode_responses=True)

bigdata_con = pymysql.connect(
    host="121.4.69.146", user='root', password='xhhg@2020', port=3306, db="big_data", use_unicode=True, charset='utf8')
bigdata_cur = bigdata_con.cursor()


def get_login():
    """获取登录token"""
    headers = {"Accept": "application/json"}
    url = 'https://api.xinhehonggu.com/api/auth/login'
    phone = '18866668888'
    password = 'xhhg2019'
    source = 'admin'
    data = {
        'method': '1',
        'phone': phone,
        'password': password,
        'source': source,
    }
    r = requests.post(url=url, data=data, headers=headers, verify=False)
    res_dict = r.json()
    token = res_dict['data']['token']
    return token


def chaxun_sqh(url, token, headers):
    with sync_playwright() as p:
        storage_state_path = f'./auth/WB_state.json'
        with open(storage_state_path) as file:
            storage_state = json.load(file)
            origins = storage_state.get('origins')
            local_stroge_list = [item.get('localStorage')
                                 for item in origins]
            for local_stroge in local_stroge_list:
                for item in local_stroge:
                    if item.get('name') == 'ACCESS_TOKEN':
                        authorization = item.get('value')
        print(f'成功读取WB登录信息:{authorization}')
        browser = p.firefox.launch()
        context = browser.new_context(
            base_url='https://cpquery.cponline.cnipa.gov.cn', storage_state=storage_state_path)
        context.set_default_timeout(300000)
        context.set_default_navigation_timeout(300000)
        page = context.new_page()
        page.set_default_timeout(300000)
        page.set_default_navigation_timeout(300000)
        page.goto(
            'https://cpquery.cponline.cnipa.gov.cn/chinesepatent/index')
        page.wait_for_load_state('networkidle')
        while redis_con.scard('外部订单申请号'):
            sqh = redis_con.spop('外部订单申请号')
            sqh = sqh.replace('ZL', '')
            print(f'开始查询:{sqh}')
            api_request_context = context.request
            post_headers = {
                "Accept": "application/json, text/plain, */*",
                "Content-Type": "application/json;charset=utf-8",
                "Authorization": 'Bearer ' + authorization,
                "userType": "USER_RZ_DAILIJIG"
            }
            sqxx_response = api_request_context.post(
                '/api/view/gn/sqxx', data={'zhuanlisqh': sqh}, headers=post_headers, timeout=0)
            try:
                patent_status_res_json = sqxx_response.json()
                patent_status_data = patent_status_res_json.get('data')
                state = patent_status_data.get(
                    'zhuluxmxx').get('zhuluxmxx').get('anjianywzt')
                if (state == '--') or (state is None):
                    state = ''
            except:
                state = ''
            res_sqh = "CN" + sqh[0:12] + "." + sqh[-1]
            print(f'{res_sqh}:{state}')
            data = {
                'token': token,
                'secret': 'th45gdk1df5rdb51',
                "patentNo": res_sqh,  # 申请号
                'lawStatus': state  # 案件状态
            }
            try:
                res = requests.put(url=url, headers=headers, data=data)
            except:
                import time
                print('5s后重试')
                time.sleep(5)
                res = requests.put(url=url, headers=headers, data=data)
            jsondata = json.loads(res.text)
            print(jsondata, sqh, state)
            print('----' * 10)
            page.reload()
            # page.wait_for_load_state('networkidle')


def get_content(url, token, headers):
    select_sql = "SELECT distinct application_number FROM `external_orders`"
    con_mysql = pymysql.connect(host="112.125.25.114", port=3306, user='python',
                                password='pythonselect', db="mykhadmin", use_unicode=True, charset='utf8')
    cur_m = con_mysql.cursor()
    cur_m.execute(select_sql)
    data_list = cur_m.fetchall()
    cur_m.close()
    con_mysql.close()
    print(f'共计:{len(data_list)}')
    for data in data_list:
        sqh = data[0].replace('ZL', '')
        redis_con.sadd('外部订单申请号', sqh)
    print('全部申请号加入redis')




if __name__ == '__main__':
    # step1: redis加入数据
    # get_content(url, token, headers)
    # step2：更新外部订单接口
    token = get_login()
    print(f'读取token:{token}')
    headers = {"Accept": "application/json"}
    url = "https://api.xinhehonggu.com/api/external_order/update"  # 系统外部订单更新接口
    # url = "http://test.api.whxhhgip.com/api/external_order/update"  # 测试接口
    # 获取案件专利信息，本地有数据有查询本地数据库，没有就网上爬  申请号在开发库的表external_orders
    from multiprocessing.pool import Pool
    p = Pool(6)
    for i in range(6):
        p.apply_async(chaxun_sqh, args=(url, token, headers))
    p.close()
    p.join()
    bigdata_cur.close()
    bigdata_con.close()
